package alkaid.eis.schedule.domain;

import java.util.Optional;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import alkaid.eis.common.exceptions.EntityMissingException;
import alkaid.eis.schedule.domain.JobInfo.State;
import alkaid.eis.schedule.domain.JobLog.Level;
import lombok.RequiredArgsConstructor;

/**
 * 任务信息服务
 *  
 * @author Lucky Yang
 * @since 0.0.1
 */
@Service
@RequiredArgsConstructor
public class JobService {
    private final JobInfoRepository jobInfoRepository;
    private final JobLogRepository jobLogRepository;

    public JobInfo findInfoById(Long jobInfoId) {
        return jobInfoRepository.findById(jobInfoId).orElseThrow(EntityMissingException::new);
    }

    @Transactional(rollbackFor = Exception.class)
    public JobInfo saveInfo(JobInfo data) {
        JobInfo entity = Optional.ofNullable(data.getId()).map(id -> {
            JobInfo jobInfo = findInfoById(id);
            jobInfo.copy(data);
            return jobInfo;
        }).orElse(data);
        return jobInfoRepository.save(entity);
    }

    public JobInfo updateInfoState(JobInfo jobInfo, State state) {
        jobInfo.setState(state);
        return jobInfoRepository.save(jobInfo);
    }

    public JobLog createLog(JobInfo job, Level level, String message) {
        return createLog(job, level, message, null);
    }

    public JobLog createLog(JobInfo job, Level level, String message, Long costTime) {
        JobLog entity = new JobLog(job, level, message, costTime);
        return jobLogRepository.save(entity);
    }
}
